//
//  MNDManageDetailViewController.m
//  minidai
//
//  Created by 谭谭伟 on 2017/5/31.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDManageDetailViewController.h"
#import "MNDTopTableViewCell.h"
#import "MNDFinanceAlertViewController.h"
#import "MNDFinanceViewController.h"
#import "MNDLoginUserModel.h"
#import "SYRefreshControl.h"
#import "MNDWebViewController.h"
#import "NSDate+JKExtension.h"
#import "NSDate+JKUtilities.h"
#import "NSDate+JKFormatter.h"
#import "MNDDetaiRootViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDUserModel.h"

@interface MNDManageDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) MNDFinaceDetailModel *detaiModel;
@property (weak, nonatomic) IBOutlet UIButton *investButton;
@property (assign, nonatomic) CGFloat cellHeight;

@property (nonatomic, copy) NSString *userPhone;

@property (nonatomic, strong) MNDUserModel *userModel;

@end

@implementation MNDManageDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showInvestButton) name:@"showInvestButton" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDetailModel:) name:@"senderBorrowCode" object:nil];
    [self setupUI];
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([MNDLoginUserModel isUserLogin]) {
        
        [self loadUserInfo];
    }
}



#pragma mark - NSNotificationAction
- (void)showInvestButton {
    self.investButton.hidden = NO;
}

- (void)getDetailModel:(NSNotification *)notification{
    self.brrowCode = [notification.object objectForKey:@"brrowCode"];
    [self loadData];
//    [self configContents];
    
}

- (void)configContents {
    
    NSDictionary *dict = @{@"detailModel":self.detaiModel, @"brrowCode":self.brrowCode};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"senderDetailModel" object:dict];

    if (self.detaiModel.borrow_status.integerValue == 2) {
        self.investButton.enabled = YES;
        [self.investButton setBackgroundImage:[UIImage imageNamed:@"finance_invest_btn"] forState:UIControlStateNormal];
    }else if(self.detaiModel.borrow_status.integerValue == 1) {
        self.investButton.enabled = NO;
        [self.investButton setBackgroundImage:nil forState:UIControlStateNormal];
        [self.investButton setBackgroundColor:[UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]];
        NSDate *startDate = [NSDate jk_dateWithString:self.detaiModel.borrow_raise_start_time format:@"yyyy-MM-dd HH:mm"];
        NSString *dateStr = [NSString stringWithFormat:@"%zd:%02zd发标", startDate.jk_hour, startDate.jk_minute];
        [self.investButton setTitle:dateStr forState:UIControlStateDisabled];
    } else {
        self.investButton.enabled = NO;
        [self.investButton setBackgroundImage:nil forState:UIControlStateNormal];
        [self.investButton setBackgroundColor:[UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]];
        if (self.detaiModel.borrow_status.integerValue >= 4) {
            [self.investButton setTitle:@"已满标" forState:UIControlStateDisabled];
        }
    }
}

#pragma mark -加载数据
- (void)loadData {
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.brrowCode}];
    
    [APIManager sendRequestWithPath:API_FINANCE_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.detaiModel = [MNDFinaceDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
            [weakSelf.tableView reloadData];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [SYRefreshControl configAfterLoading:self.tableView hasData:YES];
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:YES];
    }];
}

- (void)setupUI {
    [SYRefreshControl configGifMJRefresh:self.tableView refreshType:MJRefreshSupportRefresh beginRefresh:YES timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
    [self loadData];
        
    } loadMoreBlock:nil];
}

- (void)loadUserInfo {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark - Action
- (IBAction)goInvestAction:(UIButton *)sender {
    //未登录，先登录
    if (![MNDLoginUserModel isUserLogin]) {
        [self goToLoginVC];
        
        return;
    }
    
    //去确认投资页面
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
    MNDFinanceViewController *financeVC = [storyboard instantiateViewControllerWithIdentifier:@"financeVC"];
    financeVC.borrowCode = self.detaiModel.borrow_code;
    [self.navigationController pushViewController:financeVC animated:YES];
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDTopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDTopTableViewCell"];

    [cell.transferConditionButton addTarget:self action:@selector(showTransferConditionAlert) forControlEvents:UIControlEventTouchUpInside];
    if(self.detaiModel != nil) {
        cell.detaiModel = self.detaiModel;
    }
    return cell;
}

- (void)showTransferConditionAlert {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDFinanceAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDFinanceAlertViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    [alertVC.alertBtn bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
             alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat presentHeight = scrollView.contentOffset.y - (scrollView.contentSize.height - screenHeight);
    NSLog(@"-----%f-----",scrollView.contentOffset.y);
    NSLog(@"velocity = %f",velocity.y);
    //大于60，向上滚动
    if (velocity.y >0) {
        if (presentHeight >= 140) {
            self.investButton.hidden = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [scrollView setContentOffset:CGPointMake(0, 0)];
            });
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@1];
        }
    }
   
}

//风险揭示书
- (IBAction)checkRiskExplainAction:(UIButton *)sender {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = kRiskExplain;
    webVC.title = @"风险揭示书";
    //    webVC.naviBarHidden = NO;
    
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
